import * as THREE from "three";

// 飞线的点云实现 着色器
const FlyLinePointsShader = {
  shaderID: 'FlyLinePointsShader',

  uniforms: {
    'iTime': { value: 0.0 },
    // 分别保存：整个线段的长度；流光长度；多线段流光1，单线段流光0；背景轨迹的透明度
    'wholeAndFlowSize': { value: new THREE.Vector4(100, 10, 1, 1) },
    'flowColor': { value: new THREE.Color('#55bb5f') },
    'trackColor': { value: new THREE.Color('#0d150e') },
    // 点云中的最大顶点的大小
    'size': { value: 25.0 },
  },

  vertexShader: /* glsl */`
  uniform float iTime;
  uniform float size;
  uniform vec4 wholeAndFlowSize;
  attribute float t;
  varying float ratio;
  
  void main() {
    float whole = wholeAndFlowSize.x;
    float period = wholeAndFlowSize.y;
    bool onlySingle = wholeAndFlowSize.z == 0.0;
    float pointSize = 1.0;
    float xVal;
    ratio = -1.0;
    if (onlySingle) {
      xVal = mod(t - iTime, whole);
      ratio = smoothstep(whole - period, whole, xVal);
      pointSize = size * ratio;
    } else {
      xVal = mod(t - iTime, period * 2.0);
      // ratio = smoothstep(0.1, period - 0.01, xVal);
      ratio = smoothstep(period, period * 2.0, xVal);
      pointSize = size * ratio;
    }

    gl_PointSize = pointSize;
    gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
  }`,

  fragmentShader: /* glsl */`
	uniform vec3 flowColor;
	uniform vec3 trackColor;
	uniform vec4 wholeAndFlowSize;
  varying float ratio;
 
  void main() {
    float trackOpacity = wholeAndFlowSize.w;
    float step = step(0.05, ratio); // smoothstep(0.05, 0.99, ratio);
    vec4 color = vec4(flowColor, max(0.0, ratio)) * step + (1.0 - step) * vec4(trackColor, trackOpacity);
    
    gl_FragColor = color;
  }
`
}

export default FlyLinePointsShader;
